<!-- 订单管理 -->
<template>
  <div class="app-container">
    <!-- 搜索 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline" style="display: flex;">
      <el-form-item>
        <el-input v-model="formInline.nickname" placeholder="请输入用户昵称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="formInline.consignee" placeholder="请输入收货人名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="formInline.orderSn" placeholder="请输入订单编号" clearable></el-input>
      </el-form-item>
      <el-date-picker v-model="formInline.date" type="daterange" align="right" unlink-panels range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"
        style="width: 300px; height: 40px; margin-left: 10px" value-format="yyyy-MM-dd HH:mm:ss">
      </el-date-picker>
      <el-form-item>
        <el-select v-model="formInline.orderStatusArray" multiple filterable allow-create default-first-option
          placeholder="请选择订单状态">
          <el-option v-for="item in orderStatus" :key="item.value" :label="item.name" :value="item.index">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <div style="display: flex;">
          <el-button type="primary" @click="checkForm" icon="el-icon-search" size="mini">查找</el-button>
          <el-button type="primary" @click="downExcel" icon="el-icon-download" size="mini">导出</el-button>
        </div>
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table :data="tableData" border style="width: 100%" :header-cell-style="headerCellStyle" :cell-style="cellStyle">
      <el-table-column type="expand" empty-text="空">
        <!-- 行展开 -->
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item>
              <el-image :src="props.row.goodsVoList[0].picUrl" alt="品牌商图片" :preview-src-list="srcList"
                style="width: 40px;height: 40px;">
              </el-image>
            </el-form-item>
            <el-form-item label="商品名称:">
              <span>{{ props.row.goodsVoList[0].goodsName }}</span>
            </el-form-item>
            <el-form-item label="规格:">
              <span>{{ props.row.goodsVoList[0].specifications[0] }}</span>
            </el-form-item>
            <el-form-item label="单价:">
              <span>{{ props.row.goodsVoList[0].price }}</span>
            </el-form-item>
            <el-form-item label="数量:">
              <span>{{ props.row.goodsVoList[0].number }}</span>
            </el-form-item>
            <el-form-item label="小计:">
              <span>{{ props.row.goodsVoList[0].price }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column prop="orderSn" label="订单编号" min-width="9%" align="center">
      </el-table-column>
      <el-table-column label="用户头像" min-width="5%" align="center">
        <template slot-scope="scope">
          <el-image :src="scope.row.userAvatar" alt="品牌商图片" :preview-src-list="srcList"
            style="width: 40px;height: 40px;">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="下单用户" min-width="6%" align="center">
      </el-table-column>
      <el-table-column prop="addTime" label="下单时间" show-overflow-tooltip min-width="7%" align="center">
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" min-width="6%" align="center">
        <template slot-scope="scope">
          <el-tag>{{ getLevel(scope.row.orderStatus) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="orderPrice" label="订单金额" min-width="5%" align="center">
      </el-table-column>
      <el-table-column prop="actualPrice" label="实付金额" min-width="5%" align="center">
      </el-table-column>
      <el-table-column prop="payTime" label="支付时间" min-width="5%" align="center" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="consignee" label="收货人" min-width="5%" align="center">
        <template slot-scope="scope">
          <span style="color: red; font-weight: bold">{{
            scope.row.consignee
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="" label="收货电话" min-width="7%" align="center" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="shipSn" label="物流单号" min-width="9%" align="center">
      </el-table-column>
      <el-table-column prop="shipChannel" label="物流渠道" min-width="5%" align="center">
      </el-table-column>
      <el-table-column label="操作" min-width="22%" align="center">
        <template slot-scope="scope">
          <div class="btn">
            <el-button size="mini" @click="handleDetails(scope.$index, scope.row)" type="primary">详情</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button size="mini" @click="handleCollection(scope.$index, scope.row)" type="warning">收款</el-button>
            <el-button size="mini" @click="handleShip(scope.$index, scope.row)" type="primary">发货</el-button>
            <el-button size="mini" @click="handleRefund(scope.$index, scope.row)" type="danger">退款</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 按钮 -->
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50, 100]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 模态框1 -->
    <el-dialog title="订单详情" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="订单编号" :label-width="formLabelWidth">
          {{ form.orderSn }}
        </el-form-item>
        <el-form-item label="订单状态" :label-width="formLabelWidth">
          <el-tag>{{ getLevel(form.aftersaleStatus) }}</el-tag>
        </el-form-item>
        <el-form-item label="订单用户" :label-width="formLabelWidth">
          {{ form.nickname }}
        </el-form-item>
        <el-form-item label="用户留言" :label-width="formLabelWidth">
          {{ form.avatar }}
        </el-form-item>
        <el-form-item label="收货信息" :label-width="formLabelWidth">
          (收货人){{ form.consignee }} (手机号){{ form.mobile }} (地址){{ form.address }}
        </el-form-item>
        <el-form-item label="商品信息" :label-width="formLabelWidth">
          <el-table :data="tableDataForm" border style="width: 100%" :header-cell-style="headerCellStyle"
            :cell-style="cellStyle">
            <el-table-column prop="goodsName" label="商品名称" min-width="9%" align="center">
            </el-table-column>
            <el-table-column prop="goodsId" label="商品编号" min-width="5%" align="center"></el-table-column>
            <el-table-column prop="specifications" label="货品规格" min-width="5%" align="center"></el-table-column>
            <el-table-column prop="price" label="货品价格" min-width="5%" align="center"></el-table-column>
            <el-table-column prop="number" label="货品数量" min-width="5%" align="center"></el-table-column>
            <el-table-column prop="picUrl" label="货品图片" min-width="5%" align="center">
              <el-image :src="picUrl" alt="货品图片" :preview-src-list="srcList" style="width: 40px;height: 40px;">
              </el-image>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="费用信息" :label-width="formLabelWidth">
          (实际费用){{ form.actualPrice }}元=(商品总价){{ form.goodsPrice }}元+(快递费用){{ form.freightPrice }}元-(优惠减免){{
            form.couponPrice }}元-(积分减免){{ form.integralPrice }}元
        </el-form-item>
        <el-form-item label="支付信息" :label-width="formLabelWidth">
          (支付渠道) 微信支付 (支付时间)
        </el-form-item>
        <el-form-item label="快递信息" :label-width="formLabelWidth">
          (快递公司){{ form.shipChannel }} (快递单号){{ form.shipSn }} (发货时间) {{ form.shipTime }}
        </el-form-item>
        <el-form-item label="退款信息" :label-width="formLabelWidth">
          (退款金额) 元 (退款金额) 元 (退款备注) (退款时间)
        </el-form-item>
        <el-form-item label="收获信息" :label-width="formLabelWidth">
          (确认收货时间) {{ form.updateTime }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="printPage">打印</el-button>
      </div>
    </el-dialog>
    <!-- 模态框2 -->
    <el-dialog title="订单收款" :visible.sync="dialogFormVisible1">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="订单编号" :label-width="formLabelWidth">
          <span>确认当前订单（订单编号 {{ form.orderSn }} ) 已经完成线下收款 ？</span>
        </el-form-item>
        <el-form-item label="订单金额" :label-width="formLabelWidth">
          <el-input placeholder="请输入内容" v-model="form.actualPrice" disabled>
          </el-input>
        </el-form-item>
        <el-form-item label="付款金额" :label-width="formLabelWidth">
          <el-input placeholder="请输入金额" v-model='newMoney'>
          </el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-table :data="tableDataForm" border style="width: 100%" :header-cell-style="headerCellStyle"
            :cell-style="cellStyle">
            <el-table-column prop="goodsName" label="商品" min-width="9%" align="center">
            </el-table-column>
            <el-table-column prop="specifications" label="货品规格" min-width="5%" align="center"></el-table-column>
            <el-table-column prop="number" label="货品数量" min-width="5%" align="center"></el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="collectionFun">确定</el-button>
      </div>
    </el-dialog>
    <!-- 模态框3 -->
    <el-dialog title="订单收款" :visible.sync="dialogFormVisible2">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="快递公司" :label-width="formLabelWidth">
          <el-select v-model="form.shipChannel" placeholder="请选择发货公司">
            <el-option v-for="item in shipChannel" :key="item.code" :label="item.name" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递编号" :label-width="formLabelWidth">
          <el-input placeholder="请输入快递编号" v-model="form.shipSn">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="shipFun">确定</el-button>
      </div>
    </el-dialog>
    <!-- 模态框4 -->
    <el-dialog title="退款" :visible.sync="dialogFormVisible3">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="退款金额" :label-width="formLabelWidth">
          <el-input placeholder="退款金额" v-model="form.actualPrice" disabled>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="refundFun">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, detailsList, collectionList, delList, getShipList, shipList, refundList } from "@/api/scgl/order";
import * as XLSX from "xlsx";
import moment from "moment"
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      listLoading: true,
      // 表格数据
      tableData: [],
      queryParams: {}, //地址拼接的参数
      picUrl: '',
      srcList: [
        'http://admin.bsmall.byesame.com/wx/storage/fetch/g3ybo187ccun71o2tg03.jpg'
      ],
      // 分页
      currentPage: 1,
      size: 20,
      total: 0,
      // 查询条件
      formInline: {},
      start: '',
      end: '',
      timeArray: '',
      nickname: '',
      consignee: '',
      orderSn: '',
      orderStatusArray: '',
      // 模态框
      dialogFormVisible: false,
      form: {},
      formLabelWidth: '120px',
      rules: {
        name: [
          { required: true, message: '品牌商名称不能为空', trigger: 'blur' }
        ],
      },
      // 上传头像
      imageUrl: '',
      iconUrl: "",//默认图片
      // 导出图片
      columns: [
        { title: "订单编号", key: "orderSn" },
        { title: "下单用户", key: "userName" },
        { title: "下单时间", key: "addTime" },
        { title: "订单状态", key: "orderStatus" },
        { title: "订单金额", key: "orderPrice" },
        { title: "实付金额", key: "actualPrice" },
        { title: "支付时间", key: "message" },
        { title: "收货人", key: "consignee" },
        { title: "收货电话", key: "mobile" },
        { title: "物流单号", key: "shipSn" },
        { title: "物流渠道", key: "shipChannel" },
        { title: "收货地址", key: "address" },
      ],
      // 表头样式
      headerCellStyle({ row, column, rowIndex, columnIndex }) {
        return {
          // backgroundColor: "#EEF1F6",
          fontSize: "12px",
        }
      },
      //   设置表格样式
      cellStyle({ row, column, rowIndex, columnIndex }) {
        return {
          fontSize: "12px",
        }
      },
      // 日历
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }
        ]
      },
      // 订单状态
      orderStatus: [
        { name: '未付款', index: 101 },
        { name: '用户取消', index: 102 },
        { name: '系统取消', index: 103 },
        { name: '已付款', index: 201 },
        { name: '申请退款', index: 202 },
        { name: '已退款', index: 203 },
        { name: '已发货', index: 301 },
        { name: '用户收货', index: 401 },
        { name: '系统收货', index: 402 }
      ],
      tableDataForm: [],
      picUrl: '',
      // 收款
      dialogFormVisible1: false,
      queryParams1: {},
      newMoney: '',
      actualPrice: '',
      orderId: '',
      orderSn: '',
      // 发货
      dialogFormVisible2: false,
      shipChannel: [],
      // 退款
      dialogFormVisible3: false,
    };
  },
  created() {
    this.getParams();
    this.fetchData();
    this.iconUrl = "/api/admin/storage/create";
  },
  methods: {
    // 获取拼接参数
    getParams() {
      this.queryParams = {
        page: this.currentPage,
        limit: this.size,
        sort: 'add_time',
        order: 'desc',
        start: this.start,
        end: this.end,
        timeArray: this.timeArray,
        nickname: this.nickname,
        consignee: this.consignee,
        orderSn: this.orderSn,
        orderStatusArray: this.orderStatusArray,
      }
    },
    fetchData() {
      this.listLoading = true;
      getList(this.queryParams).then((response) => {
        console.log(response);
        this.tableData = response.data.list
        this.total = response.data.total
        this.srcList = response.data.list.map(item => item.picUrl)
        this.tableData.addTime = response.data.list.map(item => item.addTime = moment(item.addTime).format("YYYY-MM-DD"))
        this.listLoading = false;
      });
      getShipList(this.queryParams).then((response) => {
        console.log(response);
        this.shipChannel = response.data
      });
    },
    // 标签
    getLevel(orderStatus) {
      if (orderStatus == '101') {
        return '未付款'
      } else if (orderStatus == '102') {
        return '用户取消'
      } else if (orderStatus == '103') {
        return '系统取消'
      } else if (orderStatus == '201') {
        return '已付款'
      } else if (orderStatus == '202') {
        return '申请退款'
      } else if (orderStatus == '203') {
        return '已退款'
      } else if (orderStatus == '301') {
        return '已发货'
      } else if (orderStatus == '401') {
        return '用户收货'
      } else {
        return '系统收货'
      }
    },

    // 查找,防止异步
    checkForm() {
      this.currentPage = 1
      this.start = this.formInline.date && this.formInline.date[0] ? this.formInline.date[0] : ""
      this.end = this.formInline.date && this.formInline.date[1] ? this.formInline.date[1] : ""
      this.timeArray = this.formInline.date && this.formInline.date[1] ? this.formInline.date[1] : ""
      this.nickname = this.formInline.nickname
      this.consignee = this.formInline.consignee
      this.orderSn = this.formInline.orderSn
      this.orderStatusArray = this.formInline.orderStatusArray.join(',')
      this.getParams()
      this.fetchData()
    },
    // 导出
    downExcel() {
      this.$confirm("确定导出excel文件?", "提示",
        {
          type: "warning",
        }).then(() => {
          this.exportToExcel();
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消导出Excel文件",
            duration: 2000,
          });
        });
    },
    exportToExcel() {
      const data = this.tableData.map(row => {
        const newObj = {};
        this.columns.forEach(col => {
          newObj[col.title] = row[col.key];
        });
        return newObj;
      });
      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(data);
      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      // 导出Excel文件
      XLSX.writeFile(wb, '品牌商信息.xlsx');
    },

    // 详情
    handleDetails(index, row) {
      // console.log(index, row);
      this.dialogFormVisible = true
      detailsList({ id: row.id }).then((response) => {
        console.log(response);
        this.form = response.data.order
        this.form.nickname = response.data.user.nickname
        this.form.avatar = response.data.user.avatar
        this.tableDataForm = response.data.orderGoods
        this.picUrl = response.data.orderGoods[0].picUrl
        console.log(this.picUrl);

        this.listLoading = false;
      });
    },
    printPage() {
      window.print();
    },

    // 收款
    handleCollection(index, row) {
      console.log(index, row);
      this.show = 1
      this.dialogFormVisible1 = true
      this.newMoney = null
      this.form = { ...row }
      this.tableDataForm = row.goodsVoList
      this.actualPrice = row.actualPrice
      this.orderId = row.id
      this.orderSn = row.orderSn
    },
    // 获取拼接参数
    getParams1() {
      console.log(this.newMoney);
      this.queryParams1 = {
        newMoney: this.newMoney,
        oldMoney: this.actualPrice,
        orderId: this.orderId,
        orderSn: this.orderSn,
      }
    },
    // 收款确认
    collectionFun() {
      this.getParams1()
      collectionList(this.queryParams1).then((response) => {
        const difference = Math.abs(this.newMoney - this.actualPrice)
        this.$confirm(`差额${difference},是否确认提交, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dialogFormVisible1 = false;
          if (response.errno === 0) {
            console.log(response);
            this.fetchData();
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
            });
          } else {
            this.$notify({
              title: "失败",
              message: response.errmsg,
              type: "error",
            });
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      });
    },
    // 发货
    handleShip(index, row) {
      console.log(index, row);
      this.dialogFormVisible2 = true
      this.orderId = row.id
    },
    // 发货确认
    shipFun() {
      this.getParams1()
      shipList({ ...this.form, orderId: this.orderId }).then((response) => {
        this.dialogFormVisible2 = false;
        if (response.errno === 0) {
          console.log(response);
          this.fetchData();
          this.$notify({
            title: "成功",
            message: "更新成功",
            type: "success",
          });
        } else {
          this.$notify({
            title: "失败",
            message: response.errmsg,
            type: "error",
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 退款
    handleRefund(index, row) {
      console.log(index, row);
      this.dialogFormVisible3 = true
      this.form.actualPrice = row.actualPrice
      this.form.orderId = row.id
    },
    // 退单确认
    refundFun() {
      this.getParams1()
      refundList({ refundMoney: this.form.actualPrice, orderId: this.form.orderId }).then((response) => {
        this.dialogFormVisible3 = false;
        if (response.errno === 0) {
          console.log(response);
          this.fetchData();
          this.$notify({
            title: "成功",
            message: "更新成功",
            type: "success",
          });
        } else {
          this.$notify({
            title: "失败",
            message: response.errmsg,
            type: "error",
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 删除
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delList({ orderId: row.id }).then((response) => {
            console.log(response);
            this.fetchData();
            if (response.errno === 0) {
              console.log(response);
              this.fetchData();
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });
            } else {
              this.$notify({
                title: "失败",
                message: response.errmsg,
                type: "error",
              });
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getParams()
      this.fetchData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getParams()
      this.fetchData();
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/* 行展开 */
.demo-table-expand {
  font-size: 0;
  display: flex;
  justify-content: space-around;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  /* width: 50%; */
}

/* 按钮 */
.btn {
  display: flex;
  justify-content: center;
}

::v-deep .el-button+.el-button {
  margin-left: 1px;
}
</style>
